<template>
  <n-grid :x-gap="12" :y-gap="8" responsive="screen" item-responsive>
    <n-gi span="12 m:8 l:6 xl:4" 
      v-for="item,index in tasks" :key="'task_' + index">
        <n-card class="task-card">
            <template #header>
              <label class="header">
                <span class="shadow-click" @click="showForm(true, item)">{{item.name}}</span>
                <span class="icon-click"> 
                  <n-icon @click="showTaskGroupMaps(item)"><InfoRound /></n-icon>
                </span>
              </label>

            </template>
            <div class="address"> {{ item.cron }} <br> {{ item.mark }}</div>

            
            <!--
            <n-scrollbar style="max-height:10em" :trigger="'hover'" v-if="item.deviceInfo">
              <div class="spaces">
                <span v-for="di,index in item.deviceInfo" :key="'deviceInfo_'+index">  
                  {{ di.name }} &nbsp;
                  (<span class="unuse">{{di.usableSpaceStr}}</span> / <span class="total">{{di.totalSpaceStr}}</span>)
                  <br/>
                </span>
              </div>
            </n-scrollbar>
            -->
        </n-card>
    </n-gi>
  </n-grid>

  <!-- 添加和编辑弹窗 -->
  <n-modal
    v-model:show="showModal"
    class=""
    preset="dialog"
    :title="isUpdate ? '···': '...'"
    :bordered="false"
    :segmented="{content: 'soft', footer: 'soft'}"
    :show-icon="false"
    :maskClosable="false"
    :style="{ width: '40em' }"
    >

    <n-form     
      label-placement="left"
      label-width="8em"
      ref="formRef" :model="formData" :rules="rules"
      >
      <n-form-item path="name" label="名称">
        <n-input v-model:value="formData.name" placeholder="名称" />
      </n-form-item>
      
      <div style="margin-left: 8em;"><a target="_blank" href="https://www.pppet.net/">在线 cron</a></div>
      <n-form-item path="cron" label="cron 表达式">
        <n-input v-model:value="formData.cron" placeholder="cron 表达式" />
      </n-form-item>

      <n-form-item path="mark" label="说明">
        <n-input v-model:value="formData.mark" placeholder="" />
      </n-form-item>

      <n-form-item v-if="isUpdate" label="状态">
        <n-switch :rubber-band="false" :loading="activeLoading"
          :default-value="formData.active" 
          :checked-value="1" :unchecked-value="0"
          @update:value="(val) => changeActive(formData, val)" />
          
          <span v-if="formData.active == 1" class="status-active">激活</span>
          <span v-else class="status-inactive">禁用</span>
      </n-form-item>

      <n-form-item v-if="isUpdate" label=" " >
          <n-button round type="primary"  @click="showTaskGroupMaps(formData)" 
            :loading="formLoading" size="small" style="font-size:0.8em">
             编辑 Groups 
          </n-button>
      </n-form-item>

      <div style="display: flex; justify-content: flex-end">
        <n-button round type="error" style="margin-right:4px" v-if="isUpdate"
          @click="handleDelete()" :loading="formLoading">
          删除
        </n-button>
        <n-button round type="primary" style="margin-right:4px"
          @click="handleSubmit()" :loading="formLoading">
          {{ isUpdate ? '更新' : '保存' }}
        </n-button>
        <n-button round type="" @click="showModal=false" >
          关闭
        </n-button>
      </div>
    </n-form>
  </n-modal>

  <TaskGroupMaps ref="taskGroupMapsRef"></TaskGroupMaps>
</template>

<script setup>
import { inject, onMounted, ref } from 'vue'
import serverApi from '/src/api/fsync/server.js'
import TaskGroupMaps from './task-groupMaps.vue'
import { InfoRound } from '@vicons/material'
import { NSwitch } from 'naive-ui'

const tasks = ref([])

const showModal = ref(false)
const formRef = ref(null) // 表单组件
const isUpdate = ref(false) // 表单是更新
const formData = ref({}) // 表单数据
const rules = ref({
  name: [ { required: true, message: 'name required', trigger: 'blur' } ],
  cron: [ { required: true, message: 'cron required', trigger: 'blur' } ],
})
const formLoading = ref(false)
const taskGroupMapsRef = ref(null)
const activeLoading = ref(false)

const Message = inject("Message")
const Dialog = inject("Dialog")

const initTask = (task) => {
  return  { 
    id: task?.id || null,
    name: task?.name || null,
    cron: task?.cron || null,
    mark: task?.mark || null,
    active: task?.active || null,
  }
}
// 所有 tasks
const listTasks = async () => {
  await serverApi.taskList().then(res => {
    tasks.value = res.data
  })
}

// showForm(false, vo)  showForm(true, null) 
const showForm = (isUpdateOrNot, task) => {
  showModal.value = true
  isUpdate.value = isUpdateOrNot
  formData.value = initTask(task)
}
// 提交表单
const handleSubmit = async () => {
  formRef.value.validate((errors) => {
    if(errors) {
      console.error(errors)
      return
    }

  // 更新或添加
  let reqMethod = isUpdate.value ? serverApi.taskUpdate : serverApi.taskAdd
  formLoading.value = true
  reqMethod(formData.value).then(res => {
      formLoading.value = false
      closeModal()
      listTasks()
    }, err => {
      formLoading.value = false
      Message.error( err.message, { closable: true, duration: 3000 } )
      console.error(err)
    })
  })

}

// 删除
const handleDelete = async () => {
  Dialog.warning({
    title: '删除',
    content: '确认要删除这个 Task ？',
    positiveText: '删除',
    negativeText: '取消',
    maskClosable: false,
    onPositiveClick: () => {
      serverApi.taskDelete(formData.value.id).then(res => {
        closeModal()
        listTasks()
      }, err => {
        formLoading.value = false
        Message.error( err.message, { closable: true, duration: 3000 } )
        console.error(err)
      })
    },
  })
}

const showAdd = () => {
  showForm(false, null)
}
const closeModal = () => {
  showModal.value = false
  formData.value = initTask()
}

const showTaskGroupMaps = (taskObj) => {
  const dataCp = JSON.parse(JSON.stringify(taskObj))
  taskGroupMapsRef.value.show(dataCp)
}

// 修改激活状态
const changeActive = (taskData, newActive) => {
  let data = {
    id: taskData.id,
    active: newActive,
  }
  
  activeLoading.value = true
  serverApi.taskChangeActive(data).then(res => {
    activeLoading.value = false
    taskData.active = newActive
  }, err => {
    activeLoading.value = false
    Message.error( err.message, { closable: true, duration: 3000 } )
    console.error(err)
  })
}

onMounted(() => {
  listTasks()
})

defineExpose({
  showAdd,
})

</script>

<style scoped lang="scss">
.task-card{
  position: relative;
  &:hover{
    .icon-click{
      visibility: visible;
    }
  }
}
.address {
  color: #808080;
}

/*
.header{
}*/
.icon-click{
  cursor: pointer;
  font-size:0.9em;
  padding-left:0.5em;
  visibility: hidden;

  &:hover{
    color: #49c6db;
  }
}

.status-active {
  padding-left: 0.5em;
  color: green;
}
.status-inactive {
  padding-left: 0.5em;
  color: gray;
}
</style>
